import subprocess

class AdbHelper:
    def __init__(self, ip_address):
        try:
            # subprocess.run(['adb', 'start'])
            self.ip_address = ip_address
            self.init = True
        except FileNotFoundError:
            print ('adb tool not found')
    
    def set_device(self, ip_address):
        self.ip_address = ip_address

    def disconnect(self):
        if not self.init:
            return False
        subprocess.run(['adb', 'disconnect', self.ip_address], creationflags=subprocess.CREATE_NO_WINDOW)
        return True
    
    def connect(self, timeout=0):
        if not self.init:
            return False
        if timeout == 0:
            try:
                subprocess.run(['adb', 'connect', self.ip_address], timeout=timeout, creationflags=subprocess.CREATE_NO_WINDOW)
            except subprocess.TimeoutExpired:
                self.log.error('connect error')
                return False
        else:
            subprocess.run(['adb', 'connect', self.ip_address], creationflags=subprocess.CREATE_NO_WINDOW)
        return True
    def shell(self, cmd):
        if not self.init:
            return False
        subprocess.run(['adb', '-s', self.ip_address, 'shell', cmd], creationflags=subprocess.CREATE_NO_WINDOW)

    def pull(self, file1, file2):
        if not self.init:
            return False
        subprocess.run(['adb', '-s', self.ip_address, 'pull', file1, file2], creationflags=subprocess.CREATE_NO_WINDOW)

    def push(self, file1, file2):
        if not self.init:
            return False
        subprocess.run(['adb', '-s', self.ip_address, 'push', file1, file2], creationflags=subprocess.CREATE_NO_WINDOW)

    def isConnect(self):
        if not self.init:
            return False
        result = subprocess.run(['adb', 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)
        output = result.stdout.decode()
        if self.ip_address in output:
            return True
        else:
            return False
